<script lang="ts">
// 质检模板=检验规范
export default {
  name: "inspectionTemplate",
  components: { imgViewer, uploadExcel }
};
</script>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import {
  VXETable,
  VxeTableInstance,
  VxeFormPropTypes,
  VxeToolbarInstance,
  VxeFormInstance
} from "vxe-table";
import {
  addQuality,
  updateQuality,
  queryQualityPage,
  upgradeQuality,
  queryQualityDtoById,
  downloadTemplete,
  deleteQuality
} from "/@/api/quality/qualitytemplate";
import { successMessage, errorMessage, alertMessage } from "/@/utils/message";
import { queryQualityInItemAll } from "/@/api/quality/inspectionItem";
import imgViewer from "/@/components/imgViewer/index.vue";
import uploadExcel from "/@/components/uploadExcel/index.vue"; //导入文件
import { useRoute } from "vue-router";
// import qs from "qs";
const route = useRoute();
const routeName = route.name as string;
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    filterName: ""
  }
});

const xTable = ref({} as VxeTableInstance);
const xToolbar = ref({} as VxeToolbarInstance);
const xForm = ref({} as VxeFormInstance);
// 查询
const searchEvent = () => {
  const data: any = {};
  data.name = template.filterName;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  table.loading = true;
  queryQualityPage(data).then((res: any) => {
    if (res.code === 0) {
      table.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    table.loading = false;
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
const searchMethod = () => {
  const $table = xTable.value;
  // 清除所有状态
  $table.clearAll();
  return searchEvent();
};
const template = reactive({
  submitLoading: false,
  filterName: "",
  selectRow: null,
  formList: null,
  showEdit: false,
  isUpgrade: true,
  qualityData: [] as any[],
  infoData: [] as any[],
  fileList: [],
  srcList: [],
  formData: {
    id: -1,
    code: "",
    name: "",
    drawingNumber: "",
    fileNumber: "",
    qualityItemList: [{ qualityItemId: "" }]
  },
  formRules: {
    name: [{ required: true, message: "请输入检验规范名称" }],
    code: [{ required: true, message: "请输入检验规范编号" }]
  } as VxeFormPropTypes.Rules
});

// 获取质检模板=检验规范
const getQuality = () => {
  queryQualityInItemAll().then((res: any) => {
    if (res.code === 0) {
      template.qualityData = res.data;
    }
  });
};
const detailData = reactive({
  showEdit: false,
  formData: {} as any
});

const detailClose = () => {
  detailData.showEdit = false;
  detailData.formData = {} as any;
};
// 查看详情
const checkDetail = (row: any) => {
  queryQualityDtoById(row.id)
    .then((res: any) => {
      if (res.code == 0) {
        // template.formData = res.data;
        detailData.formData = res.data;
        // template.showEdit = true;
      } else {
        errorMessage(res.message);
      }
    })
    .catch((err: any) => {
      errorMessage("查询失败");
    });
  detailData.showEdit = true;
};
// 预览
const previewData = reactive({
  showEdit: false,
  formData: {} as any
});

const previewClose = () => {
  previewData.showEdit = false;
  previewData.formData = {} as any;
};
const previewEvent = (row: any) => {
  queryQualityDtoById(row.id)
    .then((res: any) => {
      if (res.code == 0) {
        previewData.formData = res.data;
      } else {
        errorMessage(res.message);
      }
    })
    .catch((err: any) => {
      errorMessage("查询失败");
    });
  previewData.showEdit = true;
};
// 新增
const insertEvent = () => {
  template.srcList = [];
  template.formData = {
    id: -1,
    code: "",
    name: "",
    drawingNumber: "",
    fileNumber: "",
    qualityItemList: [{ qualityItemId: "" }]
  };

  template.selectRow = null;
  template.showEdit = true;
};
// 修改
const editEvent = (row: any) => {
  const itemList = [];
  for (let index in row.items) {
    itemList.push({ qualityItemId: row.items[index].id });
  }
  template.formData = {
    id: row.id,
    code: row.code,
    name: row.name,
    drawingNumber: row.drawingNumber,
    fileNumber: row.fileNumber,
    qualityItemList: itemList
  };
  template.selectRow = row;
  template.isUpgrade = false;
  template.showEdit = true;
};
// 升级
// const upgradeEvent = (row: any) => {
//   const itemList = [];
//   for (let index in row.items) {
//     itemList.push({ qualityItemId: row.items[index].id });
//   }

//   template.formData = {
//     id: row.id,
//     code: row.code,
//     name: row.name,
//     drawingNumber: row.drawingNumber,
//     fileNumber: row.fileNumber,
//     qualityItemList: itemList
//   };
//   template.selectRow = row;
//   template.isUpgrade = true;
//   template.showEdit = true;
// };
// 表单提交
const submitEvent = async () => {
  const $table = xTable.value;
  const $form = xForm.value;
  const errMap = await $form.validate();
  template.formList = new FormData();
  if (template.fileList.length) {
    for (const i in template.fileList) {
      template.formList.append("files", template.fileList[i]); // 'file'可变相当于input表单的name属性\
    }
  }
  if (!errMap) {
    template.formData.qualityItemList.forEach((item, index) => {
      template.formList.append(
        `qualityItemList[${index}].qualityItemId`,
        item.qualityItemId
      );
    });
    var bool = false;
    if (template.formData.qualityItemList.length > 0) {
      for (var i = 0; i < template.formData.qualityItemList.length; i++) {
        let data = template.formData.qualityItemList[i];
        console.log(data);
        Object.keys(data).forEach(key => {
          if (key == "qualityItemId") {
            data[key] == "" ? (bool = true) : null;
          }
        });
      }
      if (bool) {
        alertMessage("请填写检查项目", "提示");
        return;
      }
    } else {
      alertMessage("请填写检查项目", "提示");
      return;
    }
    for (const i in template.formData) {
      if (i !== "qualityItemList") {
        template.formList.append(i, template.formData[i]);
      }
    }
    template.submitLoading = true;
    if (template.selectRow) {
      if (template.isUpgrade) {
        // 升级
        upgradeQuality(template.formList)
          .then((res: any) => {
            if (res.code === 0) {
              successMessage("升级成功");
              searchEvent();
              template.showEdit = false;
              handleClose();
            } else {
              errorMessage(res.message);
            }
            template.submitLoading = false;
          })
          .catch(() => {
            errorMessage("操作失败");
            template.submitLoading = false;
          });
      } else {
        // 修改
        updateQuality(template.formList)
          .then((res: any) => {
            if (res.code === 0) {
              searchEvent();
              successMessage("保存成功");
              handleClose();
              template.showEdit = false;
            } else {
              errorMessage(res.message);
            }
            template.submitLoading = false;
          })
          .catch(() => {
            errorMessage("操作失败");
            template.submitLoading = false;
          });
      }
    } else {
      // 新增
      addQuality(template.formList)
        .then((res: any) => {
          if (res.code === 0) {
            searchEvent();
            successMessage("新增成功");
            template.showEdit = false;
            handleClose();
          } else {
            errorMessage(res.message);
          }
          template.submitLoading = false;
        })
        .catch(() => {
          errorMessage("操作失败");
          template.submitLoading = false;
        });
    }
  }
};
/** 文件状态改变时调用 */
const changeFile = event => {
  template.fileList = [];
  for (let i = 0; i < event.length; i++) {
    //ready为本次上传的图片，success为已经上传的图片
    if (event[i].status == "ready") {
      template.fileList.push(event[i].raw);
    }
  }
};

// 关闭弹窗事件
const handleClose = () => {
  nextTick(() => {
    const $form = xForm.value;
    $form.reset();
    template.showEdit = false;
    template.srcList = [];
    template.fileList = [];
  });
};
// 新增质检模板=检验规范
const addTemplate = () => {
  template.formData.qualityItemList.push({ qualityItemId: "" });
};
// 删除检查项目
const deleteItem = item => {
  const index = template.formData.qualityItemList.indexOf(item);
  if (index !== -1) {
    template.formData.qualityItemList.splice(index, 1);
  }
};
// 根据查询条件导出数据
const download = () => {
  downloadTemplete()
    .then((res: any) => {
      if (res.code == 500) {
        errorMessage(res.message);
      } else {
        const fileBlob = res;
        const fileUrl = URL.createObjectURL(fileBlob); //将blob转成url地址
        const element = document.createElement("a");
        element.setAttribute("href", fileUrl);
        element.setAttribute("downLoad", "检验规范.xls");
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      }
    })
    .catch(() => {
      errorMessage("操作失败");
    });
};
// 文件上传关闭
const uploadExcelClose = () => {
  searchEvent();
};
// 删除
const deleteData = async (row: any) => {
  const type = await VXETable.modal.confirm("删除后数据将不可恢复，是否继续?");
  if (type === "confirm") {
    deleteQuality([row.id]).then((res: any) => {
      if (res.code === 0) {
        searchEvent();
        successMessage("删除成功");
      } else {
        errorMessage(res.message);
      }
    });
  }
};
// 批量删除
const ids = ref([]);
const deleteDataBatch = async v => {
  const $table = xTable.value;
  const checkboxRecords = $table.getCheckboxRecords();
  if (checkboxRecords.length == 0) {
    errorMessage("请选择删除的数据");
    return;
  }
  ids.value = [];
  checkboxRecords.map(function (currentValue) {
    ids.value.push(currentValue.id);
  });
  const type = await VXETable.modal.confirm("您确定要删除吗?");
  if (type !== "confirm") {
    return;
  }
  deleteQuality(ids.value).then((res: any) => {
    if (res.code == 0) {
      searchEvent();
      successMessage("删除成功");
    } else {
      errorMessage("删除失败");
    }
  });
};
// mounted
onMounted(() => {
  nextTick(() => {
    // 将表格和工具栏进行关联
    const $table = xTable.value;
    const $toolbar = xToolbar.value;
    $table.connect($toolbar);
    searchEvent();
    getQuality();
    table.tableHeight = changeHeight();
  });
});
</script>

<template>
  <div>
    <!-- 工具栏 -->
    <vxe-toolbar ref="xToolbar" :refresh="{ query: searchMethod }">
      <template #buttons>
        <vxe-input
          v-model="template.filterName"
          placeholder="请输入检验规范名称"
        ></vxe-input>
        <vxe-button
          icon="fa fa-search"
          status="primary"
          @click="searchEvent"
          v-auth="routeName + ':search'"
          >查询</vxe-button
        >
        <vxe-button
          icon="fa fa-plus"
          status="primary"
          @click="insertEvent"
          v-auth="routeName + ':add'"
          >新增</vxe-button
        >
        <vxe-button
          status="primary"
          icon="fa fa-download"
          v-auth="routeName + ':download'"
          @click="download"
          >下载模板</vxe-button
        >
        <upload-excel
          downLoadUrl="/quality/upload"
          @uploadExcelClose="uploadExcelClose"
        ></upload-excel>
        <vxe-button
          status="danger"
          icon="fa fa-trash-o"
          v-auth="routeName + ':delete'"
          @click="deleteDataBatch"
          >删除</vxe-button
        >
      </template>
    </vxe-toolbar>
    <!-- 列表 -->
    <vxe-table
      ref="xTable"
      class="mytable-style"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column
        type="checkbox"
        fixed="left"
        id="label"
        width="40"
      ></vxe-column>
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column
        field="code"
        title="检验规范编号"
        min-width="120"
      ></vxe-column>
      <vxe-column
        field="name"
        title="检验规范名称"
        min-width="140"
      ></vxe-column>
      <vxe-column
        field="qualityInItemName"
        title="检查项目"
        min-width="150"
      ></vxe-column>

      <!-- <vxe-column title="检查项目">
        <template #default="{ row }">
          <span v-for="(item, index) in row.items"
                :key="item.id"
                v-text="index < row.items.length - 1 ? item.name + ',' : item.name"></span>
        </template>
      </vxe-column> -->
      <vxe-column
        field="drawingNumber"
        title="图纸编号"
        min-width="160"
      ></vxe-column>
      <!-- <vxe-column
        field="fileNumber"
        title="文件编号"
        min-width="160"
      ></vxe-column> -->
      <!-- <vxe-column field="version" title="版本" min-width="100"></vxe-column> -->
      <vxe-column title="操作" width="300" fixed="right">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-eye"
            @click="checkDetail(row)"
            v-auth="routeName + ':checkDetail'"
            >查看详情</vxe-button
          >
          <vxe-button
            type="text"
            icon="fa fa-eye"
            @click="previewEvent(row)"
            v-auth="routeName + ':preview'"
            >预览</vxe-button
          >
          <!-- <vxe-button
            type="text"
            icon="fa fa-arrow-up"
            @click="upgradeEvent(row)"
            v-auth="routeName + ':upgrade'"
            >升级</vxe-button
          > -->
          <vxe-button
            type="text"
            icon="fa fa-edit"
            @click="editEvent(row)"
            v-auth="routeName + ':edit'"
            >编辑</vxe-button
          >
          <vxe-button
            type="text"
            icon="fa fa-trash-o"
            v-auth="routeName + ':delete'"
            @click="deleteData(row)"
            >删除</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 表单弹框 -->
    <vxe-modal
      v-model="template.showEdit"
      :title="template.selectRow ? '编辑&保存' : '新增&保存'"
      width="500"
      min-width="500"
      height="600"
      min-height="600"
      :loading="template.submitLoading"
      resize
      destroy-on-close
      show-footer
      @close="handleClose"
    >
      <template #default>
        <vxe-form
          ref="xForm"
          :data="template.formData"
          :rules="template.formRules"
          title-align="right"
          title-width="120"
        >
          <vxe-form-item
            field="code"
            title="检验规范编号"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.code"
                :readonly="template.selectRow == null ? false : true"
                :clearable="false"
                placeholder="请输入检验规范编号"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="name"
            title="检验规范名称"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.name"
                placeholder="请输入检验规范名称"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="drawingNumber"
            title="图纸编号"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.drawingNumber"
                placeholder="请输入图纸编号"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <!-- <vxe-form-item
            field="fileNumber"
            title="文件编号"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.fileNumber"
                placeholder="请输入文件编号"
              ></vxe-input>
            </template>
          </vxe-form-item> -->
          <template
            v-for="(item1, index) in template.formData.qualityItemList"
            :key="item1.id"
          >
            <vxe-form-item
              :span="20"
              field="qualityItemId"
              :title="'检查项目' + Number(index + 1)"
              :item-render="{}"
            >
              <template #default>
                <el-select
                  v-model="item1.qualityItemId"
                  filterable
                  placeholder="请选择检查项目"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in template.qualityData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
            </vxe-form-item>

            <vxe-form-item :span="4">
              <template #default>
                <el-button type="danger" size="small" @click="deleteItem(item1)"
                  >删除</el-button
                >
              </template>
            </vxe-form-item>
          </template>

          <vxe-form-item :span="24" title=" ">
            <template #default>
              <el-button type="primary" size="small" @click="addTemplate"
                >新增检查项目</el-button
              >
            </template>
          </vxe-form-item>
        </vxe-form>
        <img-viewer
          :list="template.srcList"
          @onChange="changeFile"
          @fileDeletes="searchEvent"
        ></img-viewer>
      </template>
      <template v-slot:footer>
        <vxe-button @click="handleClose">取 消</vxe-button>
        <vxe-button
          status="primary"
          :disabled="template.submitLoading"
          @click="submitEvent"
          >确定</vxe-button
        >
      </template>
    </vxe-modal>
    <!-- 查看详情弹框 -->
    <vxe-modal
      v-model="detailData.showEdit"
      title="查看详情"
      width="500"
      min-width="500"
      height="600"
      min-height="600"
      resize
      destroy-on-close
      show-footer
      @close="detailClose"
    >
      <template #default>
        <vxe-form
          ref="xForm"
          :data="detailData.formData"
          title-align="right"
          title-width="120"
        >
          <vxe-form-item
            field="code"
            title="检验规范编号"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              {{ data.code }}
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="name"
            title="检验规范名称"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              {{ data.name }}
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="drawingNumber"
            title="图纸编号"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              {{ data.drawingNumber }}
            </template>
          </vxe-form-item>
          <!-- <vxe-form-item
            field="fileNumber"
            title="文件编号"
            :span="24"
            :item-render="{}"
          >
            <template #default="{ data }">
              {{ data.fileNumber }}
            </template>
          </vxe-form-item> -->
          <template
            v-for="(item1, index) in detailData.formData.qualityInItemList"
            :key="item1.id"
          >
            <vxe-form-item
              :span="20"
              :title="'检查项目' + Number(index + 1)"
              :item-render="{}"
            >
              <template #default>
                {{ item1.name }}
              </template>
            </vxe-form-item>
          </template>
        </vxe-form>
        <img-viewer
          :list="detailData.formData.viewFiles"
          @onChange="changeFile"
          :disabled="true"
          @fileDeletes="searchEvent"
        ></img-viewer>
      </template>
      <template v-slot:footer>
        <vxe-button @click="detailClose">取 消</vxe-button>
      </template>
    </vxe-modal>
    <!-- 预览弹框 -->
    <vxe-modal
      v-model="previewData.showEdit"
      title="预览"
      width="80%"
      min-width="500"
      height="80%"
      resize
      destroy-on-close
      show-footer
      @close="previewClose"
    >
      <template #default>
        <img-viewer
          :list="previewData.formData.viewFiles"
          :disabled="true"
        ></img-viewer>
        <el-table
          stripe
          :data="previewData.formData.qualityInItemList"
          border
          fit
          size="mini"
          highlight-current-row
          tooltip-effect="dark"
        >
          <el-table-column type="index" width="50" label="序号">
          </el-table-column>
          <el-table-column label="检查项目" prop="name"> </el-table-column>
          <el-table-column label="技术要求" width="200" prop="standard">
          </el-table-column>
          <el-table-column label="特殊性" prop="specificity" width="200">
          </el-table-column>
          <el-table-column label="测量工具" prop="measureTools" width="200">
          </el-table-column>
          <el-table-column
            label="记录形式"
            prop="recordForm"
            width="200"
          ></el-table-column>
        </el-table>
        <iframe
          :src="
            previewData.formData.pdfUrl
              ? 'file://itts016/' + previewData.formData.pdfUrl
              : ''
          "
          style="width: 100%; min-height: 300px"
          frameborder="0"
        ></iframe>
      </template>
      <template v-slot:footer>
        <vxe-button @click="previewClose">取 消</vxe-button>
      </template>
    </vxe-modal>
  </div>
</template>
<style>
.mytable-style .vxe-body--column.col-blue {
  background-color: #60b8ff;
  color: #fff;
}
.mytable-style .vxe-body--column.col-orange {
  background-color: #f56c6c;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

// .vxe-button.type--button:not(.is--round) {
//   border-radius: 0;
// }

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
</style>
